package com.springboot.core.security;

import com.springboot.constants.SercurityConstants;
import com.springboot.sql.dao.TSysUserDao;
import com.springboot.sql.dao.entity.SysUser;
import com.springboot.utils.PasswordHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * On 2017/2/24 0024.
 * 自定义Spring-Security登录验证
 */
@Component
public class MAuthenticationProvider implements AuthenticationProvider {
    private final TSysUserDao tSysUserDao;
    private final SystemAdmin systemAdmin;

    @Autowired
    public MAuthenticationProvider(TSysUserDao tSysUserDao, SystemAdmin systemAdmin) {
        this.tSysUserDao = tSysUserDao;
        this.systemAdmin = systemAdmin;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
        try {
                //查找对应用户
                SysUser sysUser = tSysUserDao.findByUserName(username);
                if (sysUser == null)
                    throw new BadCredentialsException("username not found");
                //加盐密码验证
                if (!PasswordHash.validatePassword(password, sysUser.getPassword())) {
                    throw new BadCredentialsException("wrong password");
                }
                //权限集合获取
                Collection<? extends GrantedAuthority> authorities = sysUser.getAuthorities();
                usernamePasswordAuthenticationToken=new  UsernamePasswordAuthenticationToken(username, password, authorities);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return usernamePasswordAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
